<template>
  <div style="background-color: #fff;padding:20px">
    <div>
      <div class="flex-space-between-item">
        <div class="item flex-start-item">
          <p>员工姓名：</p><el-input placeholder="请输入员工姓名" class="input-form" v-model="searchText" />
        </div>
        <div class="flex-start-item">
          <el-button type="primary" @click="showModal(undefined, undefined)" id="add-user">添加员工</el-button>
        </div>
      </div>
    </div>
    <div style="margin-top: 20px;">
      <el-table :data="filteredStaffs" style="width: 100%" :header-cell-style="{ 'text-align': 'center' }">
        <el-table-column prop="name" label="姓名" width="140" align="center" />
        <el-table-column prop="username" label="账号" width="200" align="center" />
        <el-table-column prop="phone" label="手机号" width="150" align="center" />
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <div>{{ scope.row.status ? '启用' : '禁用' }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后操作时间" width="225" align="center" />
        <el-table-column label="操作" width="160" align="center">
          <template #default="scope">
            <el-button-group>
              <el-button plain size="small" @click="showModal(scope.row.id, scope.row)">修改</el-button>
              <el-button :type="scope.row.status ? 'danger' : 'success'" plain size="small"
                @click="disableUser(scope.row.id, scope.row.status)">{{ scope.row.status ? '禁用' : '启用' }}</el-button>
            </el-button-group>

          </template>
        </el-table-column>
      </el-table>
      <div style="width: 100%;margin-top: 10px;" class="flex-center-item">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
          layout="total, sizes, prev, pager, next, jumper" :total="totalStaffs" @current-change="handleCurrentChange" />
      </div>

    </div>
  </div>

  <el-dialog v-model="dialogVisible" width="30%" title="编辑员工">
    <el-form label-width="auto" ref="modifyForm" :rules="rules" :model="editForm">
      <el-form-item label="账号：" prop="username"><el-input v-model="editForm.username" id="i1"></el-input></el-form-item>
      <el-form-item label="姓名：" prop="name"><el-input v-model="editForm.name" id="i2"></el-input></el-form-item>
      <el-form-item label="性别：" prop="sex"><el-input v-model="editForm.sex" id="i3"></el-input></el-form-item>
      <el-form-item label="身份证号：" prop="idNumber"><el-input v-model="editForm.idNumber" id="i4"></el-input></el-form-item>
      <el-form-item label="电话号：" prop="phone"><el-input v-model="editForm.phone" id="i5"></el-input></el-form-item>
    </el-form>
    <div class="flex-end-item">
      <el-button @click="dialogVisible = false, editId = 0">取消</el-button>
      <el-button type="primary" @click="submitForm(modifyForm)" id="ok">确定</el-button>
    </div>

  </el-dialog>

</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue';
import { type Employee } from '@/types/database'
import dayjs from 'dayjs'
// header set
const headers = new Headers({
  'content-type': 'application/json',
  'Authorization': sessionStorage.getItem('token')!,
  'token': sessionStorage.getItem('token')!
})

// staff value
fetch('/api/admin/employee/page?page=1&pageSize=10', {
  headers: headers
}).then(res => res.json()).then(data => {
  if (data.code === 1) {
    staffs.shift()
    totalStaffs.value = data.data.total
    data.data.records.forEach((item: Employee) => {
      item.sex == '0' ? item.sex = '女' : item.sex = '男'
      staffs.push(item)
    })
  }
})
const totalStaffs = ref(100)
const staffs: Array<Employee> = reactive([{
  id: 1,
  name: '夏雨苗4',
  username: 'xym4',
  phone: '19198104514',
  sex: '男',
  idNumber: '1101011990010141X',
  status: 1,
}])

// input filter
const searchText = ref('')
const filteredStaffs = computed(() => {
  return staffs.filter((staff) => {
    if (searchText.value != '') {
      if (!staff.name.includes(searchText.value)) return false
    }
    return true
  })
})

// pagination
const currentPage = ref(1)
const pageSize = ref(10)
watch(pageSize, handleCurrentChange)
function handleCurrentChange() {
  console.log('currentPage', currentPage.value)
  fetch(`/api/admin/employee/page?page=${currentPage.value}&pageSize=${pageSize.value}`, {
    headers: headers
  }).then(res => res.json()).then(data => {
    if (data.code === 1) {
      staffs.splice(0)
      totalStaffs.value = data.data.total
      data.data.records.forEach((item: Employee) => {
        staffs.push(item)
      })
    }
  })
}

// modify user
const dialogVisible = ref(false)
const editId = ref(0)
import type { FormInstance } from 'element-plus'
const modifyForm = ref<FormInstance>()
const editForm = reactive({
  idNumber: '',
  name: '',
  phone: '',
  sex: '',
  username: '',
})
const rules = {
  username: [
    { required: true, message: '请输入账号', trigger: 'blur' },
    { min: 3, max: 20, message: '账号长度需在6~20个字符', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
  ],
  sex: [
    { required: true, message: '请输入性别', trigger: 'blur' },
    { pattern: /^(男|女)$/, message: '性别需为男或女', trigger: 'blur' },
  ],
  idNumber: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dX]$/, message: '请输入合法身份证号', trigger: 'blur' },
  ],
  phone: [
    { required: true, message: '请输入电话号码', trigger: 'blur' },
    { pattern: /^1[34578]\d{9}$/, message: '请输入合法的电话号码', trigger: 'blur' },
  ],
}
function showModal(id?: number, item?: Employee) {
  if (id) editId.value = id
  else editId.value = 0
  dialogVisible.value = true
  if (item) {
    Object.assign(editForm, item)
  } else {
    Object.assign(editForm, {
      idNumber: '',
      name: '',
      phone: '',
      sex: '',
      username: '',
    })
  }
}
function submitForm(form: FormInstance | undefined) {
  if (!form) return
  form.validate((valid, fields) => {
    if (valid) {
  fetch('/api/admin/employee', {
    method: editId.value ? 'PUT' : 'POST',
    headers: headers,
    body: editId.value ? JSON.stringify({
      id: editId.value,
      name: editForm.name,
      phone: editForm.phone,
      sex: editForm.sex == '男' ? '1' : '0',
      username: editForm.username,
      idNumber: editForm.idNumber,
      updateTime: dayjs().format('YYYY-MM-DD HH:mm'),
    }) : JSON.stringify(editForm)
  }).then(res => res.json())
    .then((data) => {
      if (data.code === 1) {
        ElMessage({
          message: '修改成功',
          type: 'success',
        })
        dialogVisible.value = false
        if (editId.value != 0) {
          const staff: Employee = staffs.find((item) => item.id === editId.value)!
          staff.name = editForm.name
          staff.phone = editForm.phone
          staff.sex = editForm.sex === '男' ? '男' : '女'
          staff.username = editForm.username
          staff.idNumber = editForm.idNumber
          editId.value = 0
        }
        else {
          if (currentPage.value == 1) {
            const staff: Employee = {
              id: data.data,
              name: editForm.name,
              phone: editForm.phone,
              sex: editForm.sex === '男' ? '男' : '女',
              username: editForm.username,
              idNumber: editForm.idNumber,
              status: 1,
              updateTime: console.log(dayjs().format('YYYY-MM-DD HH:mm'))!
            }
            staffs.pop()
            staffs.unshift(staff)
          }

        }
      }
      else {
        ElMessage({
          message: data.message,
          type: 'error',
        })
      }
    })
  } else {
      console.log('error submit!', fields)
    }
  })
}

// disableUser
function disableUser(id: number, status: number) {
  console.log(id, status)
  fetch(`/api/admin/employee/status/${status==1?0:1}?id=${id}`, {
    method: 'POST',
    headers: headers,
  }).then(res => res.json())
    .then((data) => {
      console.log(data)
      if (data.code === 1) {
        ElMessage({
          message: '修改成功',
          type: 'success',
        })
        const staff: Employee = staffs.find((item) => item.id === id)!
        staff.status = status ? 0 : 1
      }
      else {
        ElMessage({
          message: data.message,
          type: 'error',
        })
      }
    })
}

</script>

<style scoped>
@import '@/assets/common.css';

p {
  text-wrap: nowrap;
}

.item {
  margin-right: 10px;
}

.input-form {
  width: 150px;
}
</style>@/utils/apiConfig